package com.app.ytong.loading;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.ImageView;

import com.app.ytong.bean.BasisBean;
import com.app.ytong.bean.LoginBean;
import com.app.ytong.home.HomeIndexActivity;
import com.app.ytong.login.LoginActivity;
import com.app.ytong.R;
import com.app.ytong.basis.BasisApp;
import com.app.ytong.basis.BasisOtherActivity;
import com.app.ytong.util.MyUtils;
import com.clj.fastble.BleManager;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.util.List;

import butterknife.BindView;
import my.ActivityTool;
import my.DialogUtils;
import my.LogUtil;
import my.MySharedPreferences;
import my.http.MyHttpListener;


/**
 * 启动loading
 *
 *
 */
public class LoadingActivity extends BasisOtherActivity {

    private final static int HTTP_SESSIONCHECK = 11;

    private final int LOADING_PAUSE_TIME = 1500;

    boolean isFromPush = false;
    boolean is_pause_done = false;

    MySharedPreferences mSp;
    BasisBean mSessionCheckBean;

    @BindView(R.id.img_bg)
    ImageView img_bg;

    public static void toLoadingAllClear(Activity mContext) {
        new MySharedPreferences(mContext).putIsLogined(false);
        Intent intent = new Intent(mContext, LoadingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
//				| Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
        mContext.finish();
    }

    @Override
    public void initConfig(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        overridePendingTransition(R.anim.loading_fade_enter, R.anim.fade_exit);
        super.initConfig(savedInstanceState);

    }

    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_loading);
        super.initViews();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            LogUtil.i("loading--->启动参数异常");
            finish();

            return;

        }
        super.initData(savedInstanceState);
        Acp.getInstance(this).request(new AcpOptions.Builder()
                        .setPermissions(Manifest.permission.INTERNET
                                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                                , Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.ACCESS_FINE_LOCATION
                                , Manifest.permission.ACCESS_WIFI_STATE
                                , Manifest.permission.READ_PHONE_STATE
                                ,Manifest.permission.CAMERA
                                , Manifest.permission.ACCESS_WIFI_STATE
                                , Manifest.permission.CALL_PHONE
                                ,Manifest.permission.READ_CONTACTS
                                ,Manifest.permission.WRITE_CONTACTS
                                ,Manifest.permission.READ_SMS
                        ).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        initReal();
                        initLoading();
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
//                        BasisApp.showToast(permissions.toString() + "权限拒绝");
                        DialogUtils.DialogOKmsgFinish(mContext, "拒绝权限，结束程序");
                    }
                });

    }
    public void initReal() {
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)     //设置重连次数和重连时间间隔
                .setConnectOverTime(20000)      //设置连接超时
                .setOperateTimeout(5000);   //操作超时时间
        BleManager.getInstance().isSupportBle();
    }


    boolean isLoginRefreshDone = true;
    boolean isCountDone = false;
    private void initLoading() {
        BasisApp.isProgramExit = false;
        MySharedPreferences msp =   new MySharedPreferences(mContext);
        if(TextUtils.isEmpty(MyUtils.getIp())){
            LoginBean.logout();
            msp.putSaveVersion("");
        }else {
//            if(!TextUtils.isEmpty(Constants.URL_SERVICE) && !MyUtils.getIp().equals(Constants.URL_SERVICE)){
//                LoginBean.logout();
//                new MySharedPreferences(mContext).putSaveVersion("");
//                GreenDaoUtils.deleteAll();
//            }else if(msp.isFirstVersion(mContext)){
//                LoginBean.logout();
//            }


        }
        mSp = new MySharedPreferences(mContext);
        mHandler.sendEmptyMessageDelayed(HANDLER_LOADING_DONE, LOADING_PAUSE_TIME);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeMessages(HANDLER_LOADING_DONE);
        }
    }


    private final static int HANDLER_LOADING_DONE = 11;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_LOADING_DONE:
                    isCountDone = true;
                    GoHome();
                    break;

                default:
                    break;
            }
        }

    };

    private void GoHome() {
        if(!isCountDone)return;
        if(!isLoginRefreshDone)return;
        if(TextUtils.isEmpty(MyUtils.getIp())){
            LoginBean.logout();
        }
        if(LoginBean.isLogin()){
            ActivityTool.skipActivityAndFinish(mContext,HomeIndexActivity.class);
        }else{
            ActivityTool.skipActivityAndFinish(mContext,LoginActivity.class);
        }

//        Bundle extras = new Bundle();
//        extras.putString("url","https://case.11dom.com/yq/#kart");
//        ActivityTool.skipActivityAndFinish(mContext, WebViewX5Activity.class,extras);


    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void autoLogin() {
//		 String customNo = mSp.getCustomNo();
//		 String sessionId = mSp.getSessionId();
//		 if(TextUtils.isEmpty(customNo) || TextUtils.isEmpty(sessionId)){
//			 return;
//		 }
//		JsonHttpParams params = new JsonHttpParams();
//		params.put("customerNo", customNo);
//		params.put("sessionId", sessionId);
//
//		httpPost(LoginBean.URL_REQUERY, params, LoginBean.class, HTTP_SESSIONCHECK);
    }

    MyHttpListener myHttpListener = new MyHttpListener() {

        @Override
        public void onSuccess(int httpWhat, Object result) {
            // TODO Auto-generated method stub
            switch (httpWhat) {
                case HTTP_SESSIONCHECK:
                    if (is_pause_done) {
                        GoHome();
                    } else {
                        mSessionCheckBean = (BasisBean) result;
                    }
                    break;

                default:
                    break;
            }
        }

        @Override
        public void onFailure(int httpWhat, Object result) {
            // TODO Auto-generated method stub
            if (httpWhat == HTTP_SESSIONCHECK) {
                if (is_pause_done) {
                    GoHome();
                } else {
                    mSessionCheckBean = (BasisBean) result;
                }
            }
            super.onFailure(httpWhat, result);
        }


        @Override
        public boolean onHttpFailure(int httpWhat, Throwable arg3) {
            // TODO Auto-generated method stub
            mSessionCheckBean = new BasisBean();
            if (is_pause_done) {

                mHandler.sendEmptyMessage(HANDLER_LOADING_DONE);
            }
            return super.onHttpFailure(httpWhat, arg3);
        }

        @Override
        public void onFinish(int httpWhat) {
            // TODO Auto-generated method stub

        }
    };
}